import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import {useUserStore} from "@/stores/index.js";

const baseURL = 'http://big-event-vue-api-t.itheima.net'

var instance = axios.create({baseURL, timeout: 100000});

instance.interceptors.request.use(
    (config) => {
        var userStore = useUserStore();
        if (userStore.token) {
            config.headers.Authorization = userStore.token
        }
        return config
    },
    (err) => Promise.reject(err)
)

instance.interceptors.response.use(
    (res) => {
        if (res.data.code === 0) {
            return res
        }
        ElMessage({
            message: res.data.message || '服务异常', type: 'error'
        })
        return Promise.reject(res.data)
    },
    (err) => {
        console.log(err)
        ElMessage({message: err.response.data.message || '服务异常', type: 'error'})
        console.log(err)
        if (err.response?.status === 401) {
            router.push('/login')
        }
        return Promise.reject(err)
    }
)

export default instance;
export {baseURL}
